<template>
    <div id="app">
        <el-scrollbar wrap-class="scrollbar-wrapper" style="height:100vh;">
            <router-view/>
        </el-scrollbar>
        <iframe ref="fastgptIframe" style="opacity: 0;" @load="onIframeLoad" src="http://localhost:3000" width="0" height="0" />
    </div>
</template>

<script>
export default {
    name: 'App',
    data() {
        return {
            loginAttempts: 0,
            maxLoginAttempts: 5,
            isLoggedIn: false
        }
    },
    mounted() {
        this.isLoggedIn = localStorage.getItem('fastgpt_logged_in') === 'true'
        window.addEventListener('message', this.handleMessage)
        console.log('FastGPT iframe组件已加载')
    },
    beforeUnmount() {
        window.removeEventListener('message', this.handleMessage)
    },
    methods: {
        handleMessage(event) {
            localStorage.setItem('fastgpt_logged_in', 'true')
            this.isLoggedIn = true
        },
        onIframeLoad() {
            console.log('FastGPT iframe加载完成')
            if (this.isLoggedIn) {
                console.log('检测到已登录状态，跳过登录过程')
                return
            }
            console.log('未检测到登录状态，开始尝试登录')
            this.attemptLogin()
        },
        attemptLogin() {
            if (this.isLoggedIn) {
                return
            }
            if (this.loginAttempts >= this.maxLoginAttempts) {
                console.warn('达到最大登录尝试次数，请检查FastGPT是否正确配置')
                return
            }
            this.sendLoginInfo()
            this.loginAttempts++
            setTimeout(() => {
                if (!this.isLoggedIn) {
                    this.attemptLogin()
                }
            }, 2000)
        },
        sendLoginInfo() {
            const iframe = this.$refs.fastgptIframe
            if (iframe && iframe.contentWindow) {
                try {
                    console.log(`第${this.loginAttempts}次尝试发送登录消息`)
                    iframe.contentWindow.postMessage({
                        type: 'login',
                        username: 'root',
                        password: 'shibohengtong'
                    }, '*')
                } catch (error) {
                    console.error('发送消息失败:', error)
                }
            }
        }
    },
    metaInfo() {
        // return {
        //     title: this.$store.state.settings.dynamicTitle && this.$store.state.settings.title,
        //     titleTemplate: title => {
        //         return title ? `${title} - ${process.env.VUE_APP_TITLE}` : process.env.VUE_APP_TITLE
        //     }
        // }
    }
}
</script>
<style lang="scss">
/* element滚动条组件 隐藏水平滚动条 */
//#app .el-scrollbar__wrap {
//    overflow-x: hidden;
//}
</style>
